package com.ruoyi.common.utils;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

public enum OssUtil {

    INSTANCE;
    private final String url="https://oss.whhcr.com";
    private final String bucketName="whhcr";

    private final OSSClient client=new OSSClient("oss-cn-beijing.aliyuncs.com",
            new DefaultCredentialProvider("LTAI5tQYXGuJx22x2RqyDs8q", "VzbTtLddceHQl7gyy2ennFewQvZ7uy"),
            new ClientConfiguration());

    public String upload(String sourcePath, String targetPath) throws IOException {
        String newBucket = bucketName;
        if(!client.doesBucketExist(newBucket)){
            client.createBucket(newBucket);
        }
        return  client.putObject(newBucket, targetPath, Files.newInputStream(new File(sourcePath).toPath()))!=null ? url + "/" + targetPath : "";
    }


    public String upload(InputStream inputStream, String targetPath) {
        String newBucket = bucketName;
        if(!client.doesBucketExist(newBucket)){
            client.createBucket(newBucket);
        }
        return  client.putObject(newBucket, targetPath, inputStream)!=null ? url + "/" + targetPath : "";
    }

    public void delete(String fileName) {
       client.deleteObject(bucketName, fileName.replace(url+"/",""));
    }

}
